package com.lh.blogConsumer.service.Impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.blogCommon.constant.cst_consumer;
import com.lh.blogCommon.exception.personalBlogEx;
import com.lh.blogCommon.result.ResultCode;
import com.lh.blogCommon.util.MD5;
import com.lh.blogConsumer.entity.Member;
import com.lh.blogConsumer.mapper.MemberMapper;
import com.lh.blogConsumer.service.IMemberService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//创建时间 2021/3/16
//创建人 lh
//描述
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    @Override
    public String login(Member member) {
        String mobile = member.getMobile();
        String password = member.getPassword();

        //校验：参数是否合法
        if(StringUtils.isEmpty(mobile)
                || StringUtils.isEmpty(password)){
            throw new personalBlogEx(ResultCode.PARAM_ERROR);
        }

        //校验手机号是否存在
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        Member selectOne = baseMapper.selectOne(queryWrapper);
        if(selectOne == null){
            throw new personalBlogEx(ResultCode.LOGIN_MOBILE_ERROR);
        }

        //校验密码是否正确
        if(!MD5.encrypt(password).equals(selectOne.getPassword())){
            throw new personalBlogEx(ResultCode.LOGIN_PASSWORD_ERROR);
        }

        //校验用户是否被禁用
        if(selectOne.getDisabled()){
            throw new personalBlogEx(ResultCode.LOGIN_DISABLED_ERROR);
        }

        //登录：生成token
        //登录成功后生成JWT
        //JWT的header部分,该map可以是空的,因为有默认值{"alg":HS256,"typ":"JWT"}
        Map<String, Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,30);
        String token = JWT.create()
                .withHeader(map)//添加头部
                .withClaim("mobile",selectOne.getMobile())//添加payload
                .withClaim("username",selectOne.getNickname())
                .withClaim("avatar", selectOne.getAvatar())
                .withExpiresAt(instance.getTime())//设置过期时间
                .sign(Algorithm.HMAC256(cst_consumer.JWTCODE));//设置签名 密钥

        return token;
    }

    @Override
    public Member info(String token) {
        //创建验证对象,这里使用的加密算法和密钥必须与生成TOKEN时的相同否则无法验证
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(cst_consumer.JWTCODE)).build();
        //验证JWT
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        //获取JWT中的数据,注意数据类型一定要与添加进去的数据类型一致,否则取不到数据
        String mobile = decodedJWT.getClaim("mobile").asString();
        String username = decodedJWT.getClaim("username").asString();
        String avatar = decodedJWT.getClaim("avatar").asString();
        Date expiresAt = decodedJWT.getExpiresAt();
//        long time = expiresAt.getTime();
//        long time1 = new DateTime().toDate().getTime();
//        if(time<time1){
//            throw new personalBlogEx(ResultCode.TOKEN_EXPIRES);
//        }
        Member member = new Member();
        member.setNickname(username);
        member.setId(mobile);
        member.setAvatar(avatar);
        return member;
    }
}
